package com.usian.service.impl;

import com.usian.feign.AccountFeign;
import com.usian.feign.StockFeign;
import com.usian.mapper.OrderMapper;
import com.usian.pojo.Account;
import com.usian.pojo.Orders;
import com.usian.pojo.Stock;
import com.usian.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private StockFeign stockFeign;
    @Autowired
    private AccountFeign accountFeign;

    @Override
    @GlobalTransactional
    public void createOrder(Orders orders) {

        //1:下单  orders 插入一条数据
        int result = orderMapper.insert(orders);

        //2:扣库存  stock   update数据  skuid
        Stock stock = stockFeign.findBySkuId(orders.getSkuId());
        if(stock.getNum()>=orders.getSkuNum()){
            stock.setNum(stock.getNum()-orders.getSkuNum());
            stockFeign.DeductionStock(stock);
        }
        //3:扣金额  account  update
        Account account = accountFeign.findByUserId(orders.getUserId());
        int priceSum = (int)(orders.getPrice()*orders.getSkuNum());
        if(account.getBalance()>=priceSum){
            account.setBalance(account.getBalance()-priceSum);
            accountFeign.DeductionAmount(account);
        }
        int a=1/0;
    }
}
